﻿using System;
using System.Collections.Generic;
using System.Linq;
using Godot;
using kemocard.Scripts.Common;
using kemocard.Scripts.Module.Battle;
using kemocard.Scripts.MVC;
using kemocard.Scripts.Pawn;

namespace kemocard.Scripts.Enemy;

public partial class EnemyScript
{
    /**
     * Mod可能为null,使用时注意
     */
    protected static BattleModel Mod => GameCore.ControllerMgr.GetControllerModel<BattleModel>(ControllerType.Battle);

    public virtual void Action(BattleEnemy parent, List<string> actionId, PriorityQueue<EnemyAction, int> queue)
    {
    }

    public virtual Dictionary<string, string> GetActionDesc()
    {
        return [];
    }

    public virtual List<string> UpdateActionId()
    {
        return [];
    }

    /// <summary>
    /// 从当前战斗队友中随机检索目标列表，并优先选择嘲讽值最高的目标。
    /// </summary>
    /// <param name="targetNum">检索的数量</param>
    /// <returns>一个代表随机选择目标的BasePawn对象列表。如果没有有效目标或游戏未处于战斗状态，则返回一个空列表。</returns>
    protected static List<BasePawn> GetRandomTarget(int targetNum)
    {
        if (Mod is not { IsInBattle: true } || Mod.Teammates.Count == 0) return [];
        List<BasePawn> result = [];
        var maxTaunt = Mod.Teammates.Select(character => character.Taunt).Max();
        var isSameTaunt = Mod.Teammates.All(c => c.Taunt == maxTaunt);
        Random r = new();
        if (isSameTaunt)
        {
            // 嘲讽值全都一样的话认为没有嘲讽，随机选取目标
            var count = Mod.Teammates.Count;
            for (var i = 0; i < targetNum; i++)
            {
                result.Add(Mod.Teammates[r.Next(count)]);
            }
        }
        else
        {
            var taunts = Mod.Teammates.Where(c => c.Taunt == maxTaunt);
            var battleCharacters = taunts as BattleCharacter[] ?? taunts.ToArray();
            var count = battleCharacters.Length;
            if (count < targetNum)
            {
                var times = targetNum / count;
                for (var i = 0; i < times; i++)
                {
                    result.AddRange(battleCharacters);
                }

                // 均分次数后如果还剩余额外的次数，则随机添加目标
                var rest = targetNum % count;
                for (var i = 0; i < rest; i++)
                {
                    result.Add(battleCharacters[r.Next(count)]);
                }
            }
            else
            {
                for (var i = 0; i < targetNum; i++)
                {
                    result.Add(battleCharacters[r.Next(count)]);
                }
            }
        }

        return result;
    }

    protected static Damage CreateDamageFromOwner(BattleEnemy parent)
    {
        Damage damage = new()
        {
            User = parent,
            Role = parent.Role,
            Attribute = parent.Attribute,
            Tags = [],
            Value = 0,
            CriticalChance = parent.CriticalChance,
            CriticalRate = parent.CriticalRate
        };
        return damage;
    }
}